<template>
  <div id="webgl-container" class="webgl-container">
    <canvas id="webgl" class="webgl"/>
  </div>

  <PhysicsInfo />
</template>

<script setup>
import * as CANNON from 'cannon-es'
import {
  SphereGeometry,
  MeshNormalMaterial,
  Mesh,
  PlaneGeometry,
  MeshStandardMaterial,
  AmbientLight,
  DirectionalLight,
  DoubleSide
} from 'three'

import { useThree } from '@/hooks/use-three-hook.js'

import PhysicsInfo from './PhysicsInfo.vue'

const { scene, camera, world, initPhysics, addAnimationCallback } = useThree()

let sphereMesh, sphereBody
let planeMesh, planeBody

onMounted(() => {
  if (!scene.value || !camera.value) return

  // 初始化物理世界
  initPhysics(CANNON)

  // 创建球体几何体和材质
  const sphereGeometry = new SphereGeometry(0.5, 32, 32)
  const sphereMaterial = new MeshNormalMaterial()

  // 创建 Three.js 球体网格
  sphereMesh = new Mesh(sphereGeometry, sphereMaterial)
  sphereMesh.position.set(0, 5, 0)
  scene.value.add(sphereMesh)

  // 弹性和摩擦力
  const groundMaterial = new CANNON.Material('groundMaterial')
  const ballMaterial = new CANNON.Material('ballMaterial')
  const contactMaterial = new CANNON.ContactMaterial(
    groundMaterial,
    ballMaterial,
    {
      friction: 0.1,
      restitution: 0.7
    }
  )
  world.value.addContactMaterial(contactMaterial)

  // 创建物理球体
  sphereBody = new CANNON.Body({
    mass: 1,
    position: new CANNON.Vec3(0, 5, 0),
    shape: new CANNON.Sphere(0.5),
    material: ballMaterial
  })
  world.value.addBody(sphereBody)

  // 创建平面几何体和材质
  const planeGeometry = new PlaneGeometry(10, 10)
  const planeMaterial = new MeshStandardMaterial({
    color: 0xffffff,
    side: DoubleSide
  })

  // 创建 Three.js 平面网格
  planeMesh = new Mesh(planeGeometry, planeMaterial)
  planeMesh.rotation.x = -Math.PI / 2
  scene.value.add(planeMesh)

  // 创建物理平面
  planeBody = new CANNON.Body({
    mass: 0, // 质量为 0，表示静止不动
    shape: new CANNON.Plane(),
    material: groundMaterial
  })
  planeBody.quaternion.setFromEuler(-Math.PI / 2, 0, 0) // 旋转至水平
  world.value.addBody(planeBody)

  // 添加光源
  const ambientLight = new AmbientLight(0xffffff, 0.5)
  scene.value.add(ambientLight)

  const directionalLight = new DirectionalLight(0xffffff, 0.8)
  directionalLight.position.set(5, 10, 7)
  scene.value.add(directionalLight)

  // 同步物理世界和 Three.js 场景
  const syncPhysics = () => {
    if (sphereMesh && sphereBody) {
      sphereMesh.position.copy(sphereBody.position)
      sphereMesh.quaternion.copy(sphereBody.quaternion)
    }
  }

  addAnimationCallback(syncPhysics)
})
</script>
